package com.es.disped.web.controller.menu;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.menu.MenuService;
import com.es.disped.api.menurole.MenuRoleService;
import com.es.disped.common.constant.RecordStatus;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.Menu;
import com.es.disped.dao.model.MenuExample;
import com.es.disped.dao.model.MenuNode;
import com.es.disped.dao.model.MenuType;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@Api(value="菜单管理")
@Controller
@RequestMapping("/manage/menu")
public class MenuController extends BaseController {
	
	private final String NAMESPACE="com.es.disped.dao.mapper.menu.MenuCustomMapper";

	@Autowired
	MenuService menuService;
	@Autowired
	MenuRoleService menuRoleService;
	
	@ApiOperation(value="菜单保存",response=MsgModel.class,httpMethod="POST",notes="保存菜单-管理端")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@Transactional
	@RequestMapping(value="/save",method=RequestMethod.POST)
	public @ResponseBody MsgModel save(@RequestBody @ApiParam(name="menu",value="菜单对象",required=true) Menu menu)
	{
		int count=0;
		if(Optional.of(menu)
				.filter(name->menu.getMenuName()!=null)
				.filter(icon->menu.getMenuIcon()!=null)
				.filter(parentId->menu.getMenuParentId()!=null)
				.filter(url->menu.getMenuUrl()!=null)
				.isPresent())
		{
			//保存菜单
			menu.setMenuId(this.getUUID());
			menu.setMenuType(MenuType.MENU.getValue());
			menu.setMenuValid(RecordStatus.USEAGE.getValue());
			count=menuService.insertSelective(menu);
			//更新菜单父节点
			Menu oldParentNode=menuService.selectByPrimaryKey(menu.getMenuParentId());
			if(MenuType.MENU.getValue().equals(oldParentNode.getMenuType()))
			{
				Menu parentNode=new Menu();
				parentNode.setMenuType(MenuType.GROUP.getValue());
				MenuExample menuExample=new MenuExample();
				menuExample.createCriteria().andMenuIdEqualTo(oldParentNode.getMenuId());
				menuService.updateByExampleSelective(parentNode, menuExample);
			}
		}
		return new MsgModel(count!=0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count!=0?"":"添加失败", count!=0?menu:"");
	}
	
	@ApiOperation(value="菜单更新",response=MsgModel.class,httpMethod="POST",notes="菜单更新-管理端")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update(@RequestBody @ApiParam(name="menu",value="菜单对象",required=true) Menu menu)
	{
		int count=0;
		if(Optional.of(menu)
				.filter(mid->menu.getMenuId()!=null)
				.isPresent())
		{
			count=menuService.updateByPrimaryKeySelective(menu);
		}
		return new MsgModel(count!=0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count!=0?"":"更新失败", count!=0?menu:"");
	}
	
	@ApiOperation(value="菜单删除",response=MsgModel.class,httpMethod="POST",notes="删除菜单-管理端")
	@RequiresPermissions(value= {"admin:delete","sys:delete"},logical=Logical.OR)
	@Transactional
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public @ResponseBody MsgModel delete(@RequestBody @ApiParam(name="menu",value="菜单对象",required=true) Menu menu)
	{
		int count=0;
		if(Optional.of(menu)
				.filter(mid->menu.getMenuId()!=null)
				.filter(perantId->menu.getMenuParentId()!=null)
				.isPresent())
		{
			//删除菜单节点及子节点
			MenuExample deleteExample=new MenuExample();
			deleteExample.createCriteria().andMenuParentIdEqualTo(menu.getMenuId());
			count+=menuService.deleteByExample(deleteExample);
			count+=menuService.deleteByPrimaryKey(menu.getMenuId());
			//修改父类节点类型
			MenuExample listExample=new MenuExample();
			listExample.createCriteria().andMenuParentIdEqualTo(menu.getMenuParentId());
			List<Menu> list=menuService.selectByExample(listExample);
			if(this.isNull(list))
			{
				Menu parentNode=new Menu();
				parentNode.setMenuType(MenuType.MENU.getValue());
				MenuExample parentExample=new MenuExample();
				parentExample.createCriteria().andMenuIdEqualTo(menu.getMenuParentId());
				menuService.updateByExampleSelective(parentNode, parentExample);
			}
		}
		return new MsgModel(count!=0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count!=0?"":"删除失败", count!=0?menu:"");
	}
	
	
	@ApiOperation(value="获取Tree结构菜单",response=MsgModel.class,httpMethod="POST",notes="获取Tree结构菜单-管理端")
	@ApiImplicitParam(name="id", value="菜单ID", required=false,dataType="String")
	@RequestMapping(value="/menuTree",method=RequestMethod.POST)
	public @ResponseBody MsgModel getMenuTree(String id)
	{
		if(this.isNull(id))
		{
			id="00000000000000000000000000000000";
		}
		List<MenuNode> nodeList=new ArrayList<MenuNode>();
		List<MenuNode> rootList=this.getService().selectList(NAMESPACE+".getMenuNode", id);
		for(MenuNode menuNode:rootList)
		{
			menuNode.setChildren(getMenuNode(menuNode.getId()));
			nodeList.add(menuNode);
		}
		return new MsgModel(nodeList.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				nodeList.size()>0?"":"获取菜单为空", nodeList.size()>0?nodeList:"");
	}

    /**
     * 菜单 tree 结构加载<br>
     *
     * @param pid 菜单父ID
     * @return List<MenuNode> 菜单节点集合
     */
	private List<MenuNode> getMenuNode(String pid) {
		List<MenuNode> menuList = this.getService().selectList(NAMESPACE + ".getMenuNode", pid);
        return menuList;
	}
}
